classdef road < handle
    % This class represents one edge in the road-graph
    % any road is one-directional and contains a list of cars currently on
    % it   
    
    properties (SetAccess = public)
        firstCar        % A linked-list of cars currently on the road
        length          % The length of the road in m
        startnode       % The starting-node of the road in the road-graph
        endnode         % The ending-node of the road in the road-graph
        maxSpeedCars    % The speed-limit of the road for cars
        maxSpeedTrucks  % Speed-limit of the road for trucks
        name            % Streetname of the road
        carLengths      % End of the last car, for adding cars in sequence
    end
    
    methods
        
        function r = road(startnode, endnode, length, ...
                maxspeedcars, maxspeedtrucks)
            r.startnode = startnode;
            r.endnode = endnode;
            r.length = length;
            r.maxSpeedCars = maxspeedcars;
            r.maxSpeedTrucks = maxspeedtrucks;
        end
        
        function addCar(r, car, initial)
            if initial
                car.position = 0;
                % initially put all cars one meter apart if on the same road
                cCar = r.firstCar;                
                while ~isempty(cCar)
                    cCar.Data.position = cCar.Data.position + car.length + 1;
                    display(sprintf('Car %s at position %f', cCar.Data.name, cCar.Data.position));
                    cCar = cCar.Next;
                end
            end
            
            insertEnd(r, dlnode(car))
        end
        
        function insertEnd(r, newNode)
          if isempty(r.firstCar)
              r.firstCar = newNode;
          else
              currentNode = r.firstCar;
              prevNode = r.firstCar;
              while ~isempty(currentNode)
                  prevNode = currentNode;
                  currentNode = currentNode.Next;                    
              end
              newNode.insertAfter(prevNode);
          end
        end
    end
    
end

